package com.dyrj.pig.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dyrj.constant.SysFrameConst;
import com.dyrj.jzb.po.Po6065UnbindRelateAcct;
import com.dyrj.jzb.po.Po6066BindRelateAcctUnionPay;
import com.dyrj.jzb.po.Po6067BindRelateAccReUnionPay;
import com.dyrj.jzb.po.Po6082ApplicationTextMsgDynamicCode;
import com.dyrj.jzb.service.JzbApiService;
import com.dyrj.pig.bean.TUser;
import com.dyrj.pig.bean.TYhk;
import com.dyrj.pig.bean.TYhkExample;
import com.dyrj.pig.dao.TJzbBindcardMapper;
import com.dyrj.pig.dao.TUserMapper;
import com.dyrj.pig.dao.TYhkMapper;
import com.dyrj.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dyrj.vo.PageResultMsg;
import com.dyrj.vo.ResultMsg;
import com.dyrj.pig.service.ITJzbBindcardService;
import com.dyrj.pig.bean.TJzbBindcard;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;

/**
 * <p>
 * 见证宝--绑卡信息 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-10-16
 */
@Controller
@Slf4j
@RequestMapping("/pig/t-jzb-bindcard")
public class TJzbBindcardController {

    @Resource
    private ITJzbBindcardService service;
    @Resource
    private JzbApiService jzbApiService;
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private TYhkMapper tYhkMapper;
    @Resource
    private TJzbBindcardMapper tJzbBindcardMapper;

    @GetMapping("/index")
    @RequiresPermissions("pig:t-jzb-bindcard:index")
    public String index(ModelMap map) {
    return "pig/index_t-jzb-bindcard";
    }

    /**
    * @Title: table
    * @Description: (表格数据) 列表
    * @return PageInfo<TJzbBindcard>    返回类型
    */
    @GetMapping("/table")
    @ResponseBody
    @RequiresPermissions("pig:t-jzb-bindcard:index")
    public PageResultMsg table(TJzbBindcard record) {
        return service.table(record);
    }

    /**
    * @Title: add
    * @Description: (新增)
    * @param record
    * @return ResultMsg    返回类型
    */
    @PostMapping("/")
    @ResponseBody
    @RequiresPermissions("pig:t-jzb-bindcard:add")
    public ResultMsg add(TJzbBindcard record) {
        return service.add(record);
    }

    /**
    * @Title: info
    * @Description: (详情)
    * @param id
    * @return TJzbBindcard    返回类型
    */
    @GetMapping("/{id}")
    @ResponseBody
    @RequiresPermissions("pig:t-jzb-bindcard:info")
    public TJzbBindcard info(@PathVariable String id) {
        return service.info(id);
    }

    /**
    * @Title: update
    * @Description: (更新)
    * @param record
    * @return ResultMsg    返回类型
    */
    @PutMapping("/")
    @ResponseBody
    @RequiresPermissions("pig:t-jzb-bindcard:edit")
    public ResultMsg update(TJzbBindcard record) {
        return service.update(record);
    }

    /**
    * @Title: delete
    * @Description: (删除)
    * @param id
    * @return ResultMsg    返回类型
    */
    @DeleteMapping("/{id}")
    @ResponseBody
    @RequiresPermissions("pig:t-jzb-bindcard:delete")
    public ResultMsg delete(@PathVariable String id) {
        return service.delete(id);
    }


    /**
     * @Description: (见证宝提现绑卡 会员绑定提现账户-银联鉴权)
     * @param record
     * @return ResultMsg    返回类型
     */
    @PostMapping("/jzbbindcard")
    @ResponseBody
    public ResultMsg jzbBindCard(TJzbBindcard record) {

        String subAcctNo=record.getSubacctno();
        String tranNetMemberCode=record.getTrannetmembercode();
        String memberName=record.getMembername();
        //身份证，送1
        String memberGlobalType="1";
        String memberGlobalId=record.getMemberglobalid();
        String memberAcctNo=record.getMemberacctno();
        String acctOpenBranchName=record.getAcctopenbranchname();
        //1：本行 2：他行
        String bankType="2";
        if("平安银行".equals(acctOpenBranchName)){
            bankType="1";
        }
        String cnapsBranchId=record.getCnapsbranchid();
        String eiconBankBranchId=record.getEiconbankbranchid();
        String mobile=record.getMobile();

        Po6066BindRelateAcctUnionPay po6066BindRelateAcctUnionPay = jzbApiService.Api6066BindRelateAcctUnionPay(subAcctNo, tranNetMemberCode, memberName, memberGlobalType, memberGlobalId, memberAcctNo, bankType, acctOpenBranchName, cnapsBranchId, eiconBankBranchId, mobile);
        log.debug(JSON.toJSONString(po6066BindRelateAcctUnionPay));

        Date now = new Date();

        try{
            TJzbBindcard jzbBindcard = new TJzbBindcard();
            jzbBindcard.setId(UUIDUtil.uuid());
            jzbBindcard.setSubacctno(subAcctNo);
            jzbBindcard.setTrannetmembercode(tranNetMemberCode);
            jzbBindcard.setMembername(record.getMembername());
            jzbBindcard.setMobile(record.getMobile());
            jzbBindcard.setMemberglobalid(record.getMemberglobalid());
            jzbBindcard.setMemberacctno(record.getMemberacctno());
            jzbBindcard.setBanktype("1"); //银行卡类型（1：借记卡2：贷记卡）
            jzbBindcard.setAcctopenbranchname(record.getAcctopenbranchname());
            jzbBindcard.setCnapsbranchid(record.getCnapsbranchid());
            jzbBindcard.setEiconbankbranchid(record.getEiconbankbranchid());
            jzbBindcard.setMobile(record.getMobile());
            jzbBindcard.setInsertime(now);
            jzbBindcard.setUpdatetime(now);
            tJzbBindcardMapper.insertSelective(jzbBindcard);
        }catch (Exception e){
            e.printStackTrace();
        }

        String txnReturnMsg = po6066BindRelateAcctUnionPay.getTxnReturnMsg();
        ResultMsg resultMsg = null;
        //"txnReturnCode":"000000","txnReturnMsg":"银联验证成功，等待客户回填验证码"
        if("000000".equals(po6066BindRelateAcctUnionPay.getTxnReturnCode())){
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, txnReturnMsg);

            try{
                //防止插入重复，按照 membercode, yhkh查询是否已经存在，可能出现第一次验证成功，发送短信码，用户超时没有输入，第二次发送短信验证码，需要查询库中是否已经存在，如果已经插入，不再插入数据。
                TYhkExample tYhkExample = new TYhkExample();
                TYhkExample.Criteria tYhkcriteria = tYhkExample.createCriteria();
                tYhkcriteria.andMembercodeEqualTo(tranNetMemberCode);
                tYhkcriteria.andYhkhEqualTo(memberAcctNo);

                //绑定状态（0：未绑定，1：绑定成功，2：绑定失败，3：解绑成功，4：解绑失败）
                List<Integer> list_bdzt = new ArrayList<>();
                list_bdzt.add(0);
                list_bdzt.add(1);
                list_bdzt.add(3);
                tYhkcriteria.andBdztIn(list_bdzt);

                List<TYhk> list_tyhk = tYhkMapper.selectByExample(tYhkExample);

                if(list_tyhk!=null && list_tyhk.size()>0){

                }else{
                    TYhk tYhk = new TYhk();
                    tYhk.setId(UUIDUtil.uuid());
                    tYhk.setYhbm(Integer.valueOf(record.getYhbm()));
                    tYhk.setXm(record.getMembername());
                    tYhk.setMobile(record.getMobile());
                    tYhk.setSfzh(record.getMemberglobalid());
                    tYhk.setYhkh(record.getMemberacctno());
                    tYhk.setYhklx("1"); //银行卡类型（1：借记卡2：贷记卡）
                    tYhk.setYhmc(record.getAcctopenbranchname());
//                tYhk.setYhdm();
                    tYhk.setBdzt(0); //绑定状态（0：未绑定，1：绑定成功，2：绑定失败，3：解绑成功，4：解绑失败）
                    tYhk.setMembercode(tranNetMemberCode);
                    tYhk.setSubno(record.getSubacctno());
                    tYhk.setInsertime(now);
                    tYhk.setUpdatetime(now);
                    tYhkMapper.insertSelective(tYhk);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        }else{
            //"txnReturnCode":"ERR238","txnReturnMsg":"该会员已经绑定此帐号"
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.FAIL.CODE, txnReturnMsg);
        }
        return resultMsg;
    }

    /**
     * @Description: (见证宝提现绑卡 会员绑定提现账户-回填银联鉴权短信码)
     * @param record
     * @return ResultMsg    返回类型
     */
    @PostMapping("/jzbbindcardsms")
    @ResponseBody
    public ResultMsg jzbBindCardSms(TJzbBindcard record) {

        /*
         * subAcctNo 见证子账户的账号
         * tranNetMemberCode 交易网会员代码
         * memberAcctNo 会员的待绑定账户的账号
         * messageCheckCode 短信验证码
         */
        String subAcctNo=record.getSubacctno();
        String tranNetMemberCode=record.getTrannetmembercode();
        String memberAcctNo=record.getMemberacctno();
        String messageCheckCode=record.getMessagecheckcode();

        Po6067BindRelateAccReUnionPay po6067BindRelateAccReUnionPay = jzbApiService.Api6067BindRelateAccReUnionPay(subAcctNo, tranNetMemberCode, memberAcctNo, messageCheckCode);
        log.debug(JSON.toJSONString(po6067BindRelateAccReUnionPay));

        String txnReturnMsg = po6067BindRelateAccReUnionPay.getTxnReturnMsg();
        ResultMsg resultMsg = null;
        //"txnReturnCode":"000000","txnReturnMsg":"银联验证成功，等待客户回填验证码"
        if("000000".equals(po6067BindRelateAccReUnionPay.getTxnReturnCode())){
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, txnReturnMsg);

            try{
                //根据 membercode，yhkh 查询用户绑定的银行卡，删除绑卡信息。
                TYhkExample tYhkExample = new TYhkExample();
                TYhkExample.Criteria tYhkcriteria = tYhkExample.createCriteria();
                tYhkcriteria.andMembercodeEqualTo(tranNetMemberCode);
                tYhkcriteria.andYhkhEqualTo(memberAcctNo);
                TYhk tYhk_update = new TYhk();
                tYhk_update.setBdzt(1);//绑定状态（0：未绑定，1：绑定成功，2：绑定失败，3：解绑成功，4：解绑失败）
                tYhk_update.setUpdatetime(new Date());
                tYhkMapper.updateByExampleSelective(tYhk_update, tYhkExample);
//        tYhkMapper.deleteByExample(tYhkExample);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else{
            //"txnReturnCode":"ERR238","txnReturnMsg":"该会员已经绑定此帐号"
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.FAIL.CODE, txnReturnMsg);

        }
        return resultMsg;
    }


    /**
     * @Description: (见证宝解绑银行卡)
     * @param record
     * @return ResultMsg    返回类型
     */
    @PostMapping("/jzbunbinddard")
    @ResponseBody
    public ResultMsg jzbUnBindCard(TJzbBindcard record) {
        String subAcctNo=record.getSubacctno();
        String tranNetMemberCode=record.getTrannetmembercode();
        String memberAcctNo=record.getMemberacctno();


        Po6065UnbindRelateAcct po6065UnbindRelateAcct = jzbApiService.Api6065UnbindRelateAcct(subAcctNo, tranNetMemberCode, memberAcctNo);
        log.debug(JSON.toJSONString(po6065UnbindRelateAcct));

        String txnReturnMsg = po6065UnbindRelateAcct.getTxnReturnMsg();
        ResultMsg resultMsg = null;
        //"txnReturnCode":"000000","txnReturnMsg":"交易成功"
        if("000000".equals(po6065UnbindRelateAcct.getTxnReturnCode())){
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, txnReturnMsg);

            try{
                //根据 membercode，yhkh 查询用户绑定的银行卡，删除绑卡信息。
                TYhkExample tYhkExample = new TYhkExample();
                TYhkExample.Criteria tYhkcriteria = tYhkExample.createCriteria();
                tYhkcriteria.andMembercodeEqualTo(tranNetMemberCode);
                tYhkcriteria.andYhkhEqualTo(memberAcctNo);
                TYhk tYhk_update = new TYhk();
                tYhk_update.setBdzt(3);//绑定状态（0：未绑定，1：绑定成功，2：绑定失败，3：解绑成功，4：解绑失败）
                tYhk_update.setUpdatetime(new Date());
                tYhkMapper.updateByExampleSelective(tYhk_update, tYhkExample);
//        tYhkMapper.deleteByExample(tYhkExample);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else{
            resultMsg = new ResultMsg(SysFrameConst.ResultCode.FAIL.CODE, txnReturnMsg);
        }
        return resultMsg;

    }


    /**
     * @Description: (见证宝提现发送验证码  申请提现或支付短信动态码)
     * @param record
     * @return ResultMsg    返回类型
     */
    @PostMapping("/tixiansms")
    @ResponseBody
    public ResultMsg jzbTixianSms(TJzbBindcard record) {

        /*
         * subAcctNo 见证子账户的账号
         * tranType 交易类型 1：提现 2：支付 3：批次号支付 4：批次号作废
         * tranAmt 交易金额 按批次号提现时非必输
         * bankCardNo 银行卡号
         * orderNo 订单号 按批次号提现时，此字段必须，上送批次号字段
         */
        //闻荷怡
        String subAcctNo=record.getSubacctno();
        String tranNetMemberCode=record.getTrannetmembercode();
//        String bankCardNo="6230580000051480254";
//        String tranType="1";
//        String tranAmt="0.10";
//        String orderNo="";
//
//        Po6082ApplicationTextMsgDynamicCode po6082ApplicationTextMsgDynamicCode = jzbApiService.Api6082ApplicationTextMsgDynamicCode(subAcctNo, tranNetMemberCode, tranType, tranAmt, bankCardNo, orderNo);
//        log.debug(JSON.toJSONString(po6082ApplicationTextMsgDynamicCode));

//        String txnReturnMsg = po6082ApplicationTextMsgDynamicCode.getTxnReturnMsg();
//        ResultMsg resultMsg = null;
//        //"txnReturnCode":"000000","txnReturnMsg":"银联验证成功，等待客户回填验证码"
//        if("000000".equals(po6082ApplicationTextMsgDynamicCode.getTxnReturnCode())){
//            resultMsg = new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, txnReturnMsg);
//
//            try{
//                //根据 membercode，yhkh 查询用户绑定的银行卡，删除绑卡信息。
//                TYhkExample tYhkExample = new TYhkExample();
//                TYhkExample.Criteria tYhkcriteria = tYhkExample.createCriteria();
//                tYhkcriteria.andMembercodeEqualTo(tranNetMemberCode);
////                tYhkcriteria.andYhkhEqualTo(memberAcctNo);
//                TYhk tYhk_update = new TYhk();
//                tYhk_update.setBdzt(1);//绑定状态（0：未绑定，1：绑定成功，2：绑定失败，3：解绑成功，4：解绑失败）
//                tYhk_update.setUpdatetime(new Date());
//                tYhkMapper.updateByExampleSelective(tYhk_update, tYhkExample);
////        tYhkMapper.deleteByExample(tYhkExample);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//
//        }else{
//            //"txnReturnCode":"ERR238","txnReturnMsg":"该会员已经绑定此帐号"
//            resultMsg = new ResultMsg(SysFrameConst.ResultCode.FAIL.CODE, txnReturnMsg);
//
//        }
        ResultMsg resultMsg = new ResultMsg(SysFrameConst.ResultCode.FAIL.CODE, "");
        return resultMsg;
    }


}
